<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <title>选课页面</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <style>
        /* 添加自定义样式 */
        #backToHomepage {
            position: fixed;
            bottom: 20px; /* 距离底部20px */
            left: 20px;   /* 距离左边20px */
        }
    </style>
</head>

<body>
<div class="container">
    <h1 class="text-center mt-5">选课页面</h1>

    <h2 class="mt-5">可选课程</h2>
    <div id="noAvailableCourses" style="display: none;" class="alert alert-warning">
        无可选课程
    </div>
    <table class="table">
        <thead>
        <tr>
            <th>课程名称</th>
            <th>学分</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="courseTableBody">
        <!-- 动态加载课程数据 -->
        </tbody>
    </table>

    <h2 class="mt-5">已选课程</h2>
    <div id="noSelectedCourses" style="display: none;" class="alert alert-info">
        你还没有已选课程，快去选课吧！
    </div>
    <table class="table">
        <thead>
        <tr>
            <th>课程名称</th>
            <th>学分</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="selectedCoursesBody">
        <!-- 动态加载已选课程数据 -->
        </tbody>
    </table>

    <!-- 返回主页按钮 -->
    <div class="text-center mt-5">
        <button class="btn btn-secondary" id="backToHomepage">返回主页</button>
    </div>
</div>

<script>
    $(document).ready(function () {
        const userId = localStorage.getItem('userId');

        loadSelectedCourses(userId);
        loadCourses();

        // 返回主页按钮功能
        $('#backToHomepage').click(function () {
            window.location.href = 'index.html'; // 修改为你的主页路径
        });

        // 选课功能
        $(document).on('click', '#courseTableBody .btn-primary', function () {
            const courseId = $(this).data('id');
            enrollCourse(courseId);
        });

        // 退课功能
        $(document).on('click', '.dropBtn', function () {
            const courseId = $(this).data('id');
            const enrollmentData = {
                userId: userId,
                courseId: courseId // 使用逻辑外键
            };

            $.ajax({
                url: 'http://localhost:8088/users/cancelCourse',
                type: 'DELETE',
                contentType: 'application/json',
                data: JSON.stringify(enrollmentData),
                success: function (response) {
                    alert(response.msg || '退课成功');
                    // 退课成功后重新加载课程列表
                    loadSelectedCourses(userId); // 重新加载已选课程
                    loadCourses();  // 重新加载可选课程
                },
                error: function () {
                    alert('退课失败，请重试！');
                }
            });
        });
    });

    function loadSelectedCourses(userId) {
        $.ajax({
            url: `http://localhost:8088/users/findAllCourse/${userId}`, // 获取已选课程
            type: 'GET',
            success: function (response) {
                const courses = response.data || [];
                const selectedCoursesBody = $('#selectedCoursesBody');
                selectedCoursesBody.empty();

                if (courses.length === 0) {
                    $('#noSelectedCourses').show();
                } else {
                    $('#noSelectedCourses').hide();
                    courses.forEach(course => {
                        const row = `<tr>
                            <td>${course.courseName}</td>
                            <td>${course.credits}</td>
                            <td><button class="btn btn-danger dropBtn" data-id="${course.id}">退课</button></td>
                        </tr>`;
                        selectedCoursesBody.append(row);
                    });
                }
            },
            error: function () {
                alert('加载已选课程失败，请重试！');
            }
        });
    }

    function loadCourses() {
        $.ajax({
            url: 'http://localhost:8088/users/course', // 获取可选课程
            type: 'GET',
            success: function (response) {
                const courses = response.data || [];
                const courseTableBody = $('#courseTableBody');
                const selectedCourseIds = [];

                // 获取已选课程ID以便于过滤
                $('#selectedCoursesBody tr').each(function () {
                    const courseId = $(this).find('td:last button').data('id');
                    selectedCourseIds.push(courseId);
                });

                const availableCourses = courses.filter(course => !selectedCourseIds.includes(course.id));

                courseTableBody.empty(); // 清空表格
                if (availableCourses.length === 0) {
                    $('#noAvailableCourses').show();
                } else {
                    $('#noAvailableCourses').hide();
                    availableCourses.forEach(course => {
                        const row = `<tr>
                            <td>${course.courseName}</td>
                            <td>${course.credits}</td>
                            <td><button class="btn btn-primary" data-id="${course.id}">选课</button></td>
                        </tr>`;
                        courseTableBody.append(row);
                    });
                }
            },
            error: function () {
                alert('加载课程失败，请重试！');
            }
        });
    }

    function enrollCourse(courseId) {
        const enrollmentData = {
            userId: localStorage.getItem('userId'),
            courseId: courseId,
            enrollmentDate: new Date().toISOString()
        };

        $.ajax({
            url: 'http://localhost:8088/users/selectCourse',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(enrollmentData),
            success: function () {
                alert("选课成功");
                loadSelectedCourses(localStorage.getItem('userId')); // 刷新已选课程
                loadCourses(); // 刷新可选课程
            },
            error: function () {
                alert('选课失败，请重试！');
            }
        });
    }
</script>

</body>

</html>
